/*
** get_next_line.c for get_next_line in /home/yang_j/rendu/CPE_2013_getnextline
** 
** Made by yang jie
** Login   <yang_j@epitech.net>
** 
** Started on  Mon Nov 25 20:05:22 2013 yang jie
** Last update Sat Dec  7 19:50:29 2013 georgi_v
*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include "my.h"

#define SIZE 50

static int	buff_i;
static int	ret;

char	*my_clean(char *str)
{
  int	i;

  i = 0;
  while (i < SIZE)
    {
      str[i] = '\0';
      i = i + 1;
    }
  return (str);
}

char	*my_realloc(char *dest, int alloc)
{
  char	*new_dest;
  int	i;

  new_dest = malloc(sizeof(new_dest) * (SIZE * alloc) + 1);
  if (new_dest == NULL)
    {
      write(1, "malloc error!", 13);
      ret = -1;
      return (NULL);
    }
  i = 0;
  while (dest[i] != '\0')
    {
      new_dest[i] = dest[i];
      i = i + 1;
    }
  new_dest[i] = '\0';
  free(dest);
  return (new_dest);
}

char		*copy_from_buff(char *dest, char *buffer, int i)
{
  static int	alloc;

  if (alloc == 0)
    alloc = 1;
  if (i >= (SIZE * (alloc)))
    {
      alloc++;
      dest = my_realloc(dest, alloc);
    }
  else if (i < SIZE)
    alloc = 1;
  dest[i] =buffer[buff_i];
  buff_i++;
  return (dest);
}

char		*my_get_nextline(char *buffer, int fd, char *dest)
{
  int		i;

  i = 0;
  while (ret > 0)
    {
      if (buffer[buff_i] == '\n')
	{
	  dest[i] = '\0';
	  buff_i++;
	  return (dest);
	}
      else if (buff_i == ret)
	{
	  buffer = my_clean(buffer);
	  buff_i = 0;
	  ret = read(fd, buffer, SIZE);
	}
      else
	{
	  dest = copy_from_buff(dest, buffer, i);
	  i++;
	}
    }
  return (NULL);
}

char		*get_next_line(const int fd)
{
  static char	buffer[SIZE];
  char		*dest;

  if (fd == -1)
    {
      write(2, "No such file or directory\n", 27);
      return (NULL);
    }
  if (buff_i == 0)
    {
      ret = read(fd, buffer, SIZE);
      if (ret == 0 || ret == -1)
	{
	  if (ret == -1)
	    write(2, "error on read file\n", 17);
	  return (NULL);
	}
      buffer[ret] = '\0';
    }
  if ((dest = malloc(sizeof(dest) * SIZE + 1)) == NULL)
    return (NULL);
  dest = my_get_nextline(buffer, fd, dest);
  return (dest);
}
